//
//  WSDataReportFilterManager.m
//  microvision
//
//  Created by zhenjingxiong on 2021/3/2.
//  Copyright © 2021 tencent. All rights reserved.
//

#import "WSDataReportFilterManager.h"
#import "WSDataReportHelper.h"
#import "WSDataReportDataSourceManager.h"
#import "WSDataReportFilterItem.h"
#import "WSDataReportConfig.h"

@interface WSDataReportFilterManager()

@property (nonatomic, strong) NSHashTable<id<WSDataReportManagerDelegate>> *observerList;

@property (nonatomic, strong) NSLock *lock;

@end


@implementation WSDataReportFilterManager

+ (instancetype)instance {
    static WSDataReportFilterManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[WSDataReportFilterManager alloc] init];
    });
    return instance;
}

#pragma mark - Public Method

- (void)updateFilterDataSource {
    NSMutableArray<NSDictionary *> *searchKeyfilterDataSource = [self filterDataSourceFromSearchKey];
    NSMutableArray<NSDictionary *> *filterItemfilterDataSource = [self filterDataSourceFromFilterItem:searchKeyfilterDataSource];
    self.filterDataSource = filterItemfilterDataSource;
    
    for (id<WSDataReportManagerDelegate> delegate in self.observerList) {
        if ([delegate respondsToSelector:@selector(updatedFilterDataSource)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [delegate updatedFilterDataSource];
            });
        }
    }
}

// 清除筛选条件，还原数据
- (void)clearFilterFilterConditions {
    // 筛选条置空处理，还原数据源
    self.serachKey = @"";
    for (WSDataReportFilterItem *filterItem in [WSDataReportConfig instance].dataFilterItemArray) {
        filterItem.reportDatafilterValues = @[];
    }
    self.filterDataSource = [WSDataReportDataSourceManager instance].dataReportdataSource;

    for (id<WSDataReportManagerDelegate> delegate in self.observerList) {
        if ([delegate respondsToSelector:@selector(updateFilterConditionViewContent:)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [delegate updateFilterConditionViewContent:@""];
                [delegate updatedFilterDataSource];
            });
        }
    }
}

// 通过筛选条件更新数据
- (void)updateDataByFilterConditions {
    // 更新筛选条件视图显示内容
    [self updateFilterConditionView];
    // 更新过滤数据源，刷新列表
    [self updateFilterDataSource];
}

- (NSString *)filterConditionViewContent {
    NSMutableDictionary *newInfo = [NSMutableDictionary new];
    for (WSDataReportFilterItem *filterItem in [WSDataReportConfig instance].dataFilterItemArray) {
        if (filterItem.reportDatafilterValues && filterItem.reportDatafilterValues.count) {
            [newInfo setValue:filterItem.reportDatafilterValues forKey:filterItem.reportDataFilterKey];
        }
    }
    if (newInfo.allKeys.count == 0) {
        return @"";
    }
    NSString *filterConditionViewContent = [WSDataReportHelper jsonStringForDictionary:newInfo];
    return filterConditionViewContent;
}

- (void)updateSearchKey:(NSString *)searchKey {
    [WSDataReportFilterManager instance].serachKey = searchKey;
    [self updateFilterDataSource];
    
}


#pragma mark - Private Method

- (void)updateFilterConditionView {
    NSString *filterConditionViewContent = [self filterConditionViewContent];
    for (id<WSDataReportManagerDelegate> delegate in self.observerList) {
        if ([delegate respondsToSelector:@selector(updateFilterConditionViewContent:)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [delegate updateFilterConditionViewContent:filterConditionViewContent];
            });
        }
    }
}


- (NSMutableArray *)filterDataSourceFromSearchKey {
    NSMutableArray *array = [NSMutableArray array];
    if (![WSDataReportFilterManager instance].serachKey.length) {
        array = [WSDataReportDataSourceManager instance].dataReportdataSource.mutableCopy;
    } else {
        for (NSDictionary *info in [WSDataReportDataSourceManager instance].dataReportdataSource) {
            NSString *jsonStr = [WSDataReportHelper jsonStringForDictionary:info];
            if ([jsonStr containsString:[WSDataReportFilterManager instance].serachKey]) {
                [array addObject:info];
            }
        }
    }
    return array;
}

- (NSMutableArray<NSDictionary *> *)filterDataSourceFromFilterItem:(NSMutableArray<NSDictionary *> *)dataSource {
    NSMutableArray *newDataSoure = [NSMutableArray array];
    for (NSDictionary *reportDictionray in dataSource) {
        BOOL isMatchFilterItem = YES;
        for (WSDataReportFilterItem *filterItem in [WSDataReportConfig instance].dataFilterItemArray) {
            // 如果过滤条件array为nil，或者count为0，则不关心该过滤条件
            if (!filterItem.reportDatafilterValues.count) {
                continue;
            }
            
            NSObject *result = reportDictionray[filterItem.reportDataFilterKey];
            if ([WSDataReportHelper isEmptyForObject:result]) {
                isMatchFilterItem = NO;
                break;
            }
            
            if ([WSDataReportHelper nonContainerClassObject:result]) {
                NSString *resultObj = [WSDataReportHelper stringValueForNonContainerClassObject:result];
                if (![WSDataReportHelper isContainsResultObject:filterItem.reportDatafilterValues withResultObject:resultObj]) {
                    isMatchFilterItem = NO;
                    break;
                }
                
            }  else if ([WSDataReportHelper isContainerClassObject:result]) {
                NSString *resultObj = [WSDataReportHelper jsonStringForContainerClassObject:result];
                if (![WSDataReportHelper isContainsResultObject:filterItem.reportDatafilterValues withResultObject:resultObj]) {
                    isMatchFilterItem = NO;
                    break;
                }
                
            } else {
                isMatchFilterItem = NO;
                break;
            }
        }
        if (isMatchFilterItem) {
            [newDataSoure addObject:reportDictionray];
        }
    }
    return newDataSoure;
}


#pragma mark - Observer Method

- (void)registerObserver:(id<WSDataReportManagerDelegate>)observer {
    [self.lock lock];
    [self.observerList addObject:observer];
    [self.lock unlock];
}

- (void)unregisterObserver:(id<WSDataReportManagerDelegate>)observer {
    [self.lock lock];
    [self.observerList removeObject:observer];
    [self.lock unlock];
}

#pragma mark - Accessor Method

- (NSLock *)lock {
    if (!_lock) {
        _lock = [[NSLock alloc] init];
    }
    return _lock;
}

- (NSHashTable<id<WSDataReportManagerDelegate>> *)observerList {
    if (!_observerList) {
        _observerList = [NSHashTable weakObjectsHashTable];
    }
    return _observerList;
}

- (NSArray<NSDictionary *> *)filterDataSource {
    if (!_filterDataSource) {
        _filterDataSource = [WSDataReportDataSourceManager instance].dataReportdataSource;
    }
    return _filterDataSource;
}


@end
